import { createRouter, createWebHistory } from "vue-router";
import AdminView from "../views/AdminView.vue";
import NotFound from "../views/NotFound.vue"
// import routeList from "../utils/routeconfig"
import { useUserStore } from "@/stores/user.js"


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("../views/LoginView.vue"),
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: NotFound
    },
  ],
});
const generateRote = () => {
  const asyncRoute = {
    path: "/",
    name: "admin",
    component: AdminView,
    redirect: "/home",
    children: []
  }
  let modules = import.meta.glob('../views/*.vue')
  const paraseRoute = (route) => {
    if (route.path) {
      asyncRoute.children.push({
        path: route.path,
        name: route.name,
        component: modules[`../${route.componentPath}`],
        //为面包屑服务
        meta: {
          label: route.lable
        }
      })
    }
    else {
      route.children.forEach(item => {
        paraseRoute(item)
      })
    }
  }
  //遍历配置permission添加路由
  const userStore = useUserStore()
  // console.log(userStore.getUser.permission, "--------------");
  // let routeList = JSON.parse(localStorage.getItem("permission")) || []
  const routeList = userStore.getUser.permission
  routeList.forEach(route => {
    paraseRoute(route)
  })
  return asyncRoute
}
// //添加路由
// router.addRoute(generateRote())
//编写路由守卫 根据当前用户动态添加路由
router.beforeEach((t, f, n) => {
  //确保权限路由只添加一次
  //进入页面不是登陆（登录页面不需要动态路由）
  //进入后续页面时还没有添加过admin路由
  if (t.path != "/login" && !router.hasRoute("admin")) {
    router.addRoute(generateRote())
    n(t.path)
  }
  else {
    n()
  }
})
export default router;
